﻿//**********************************************************
//Copyright(C)2010 By 波特商网公司 版权所有。
//
//文件名：
//文件功能：用于主框架加载插件
//
//创建标识：齐李平 || 2011-04-01
//
//修改标识：
//修改描述：
//**********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using Hmc.IM.Common.Plugin;
using Hmc.IM.Common;



namespace Hmc.IM.Client.Core
{
    /// <summary>
    /// 主框架插件加载帮助类
    /// </summary>
    public class PluginLoader
    {
        /// <summary>
        /// 插件List
        /// </summary>
        public static List<IPlugin> plugins = new List<IPlugin>();

        /// <summary>
        /// 验证dll是否是需要加载的插件
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private static bool IsValidPlugin(Type t)
        {
            bool ret = false;
            Type[] interfaces = t.GetInterfaces();
            foreach (Type theInterface in interfaces)
            {
                if (theInterface.FullName == "Hmc.IM.Common.Plugin.IPlugin")
                {
                    ret = true;
                    break;
                }
            }
            return ret;
        }

        /// <summary>
        /// 加载插件
        /// </summary>
        public static void LoadAllPlugins()
        {
            string[] files = Directory.GetFiles(Application.StartupPath + "\\plugin\\");
            PluginAttributeAttribute typeAttribute = new PluginAttributeAttribute();
            //int i = 0;
            #region 添加插件到List
            foreach (string file in files)
            {
                string ext = file.Substring(file.LastIndexOf("."));
                if (ext != ".dll") continue;
                try
                {
                    Assembly tmp = Assembly.LoadFile(file);
                    Type[] types = tmp.GetTypes();

                    foreach (Type t in types)
                    {
                        if (IsValidPlugin(t))
                        {
                            System.Diagnostics.Debug.WriteLine(t.FullName);
                            IPlugin plugin = (IPlugin)tmp.CreateInstance(t.FullName);
                            plugins.Add(plugin);
                        }
                    }
                }
                catch (Exception err)
                {
                    //Recorder.Write(err);
                    throw err;
                }
            } 
            #endregion

            plugins = (from p in plugins
                         orderby p.PluginIndex descending
                         select p).ToList();
        }

    }
}
